<?php

declare(strict_types=1);

namespace App\Services;

use App\Entity\AreaEntity;
use App\Entity\UserAddressEntity;
use App\Models\Area;
use App\Models\UserAddress;
use App\Services\api\ILocationService;

class LocationNewService implements ILocationService
{
    /**
     * {@inheritdoc}
     */
    public function getCityById(int $cityId)
    {
        return AreaEntity::find($cityId);
    }

    /**
     * {@inheritdoc}
     */
    public function getCityByAreaName(string $areaName)
    {
        $model = Area::where('areaname', '=', $areaName)->first();
        if ($model === null) {
            return $model;
        } else {
            return new AreaEntity($model);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getCityNameById(int $cityId)
    {
        $areaEntity = $this->getCityById($cityId);

        return $areaEntity ? $areaEntity->getAreaname() : '';
    }

    /**
     * {@inheritdoc}
     */
    public function getCityNamesByIds(string $cityIds)
    {
        if (!$cityIds) {
            return '全国通用';
        }

        $collection = Area::whereIn('id', explode(',', $cityIds))->get();

        return implode(',', array_column($collection->toArray(), 'areaname'));
    }

    /**
     * {@inheritdoc}
     */
    public function getLastSetUserAddress(int $userId)
    {
        $userModel = UserAddress::where('user_id', '=', $userId)
            ->orderBy('created_at', 'desc')
            ->first();

        return $userModel === null ? null : new UserAddressEntity($userModel);
    }

    /**
     * {@inheritdoc}
     */
    public function getDefaultUserAddress(int $userId)
    {
        $userModel = UserAddress::query()
            ->where('user_id', '=', $userId)
            ->where('isdefault', '=', 1)
            ->first();

        return $userModel === null ? null : new UserAddressEntity($userModel);
    }
}
